package com.lqwu.mallchatserver.common.event.listener;

import com.lqwu.mallchatserver.common.event.UserRegisterEvent;
import com.lqwu.mallchatserver.user.model.entry.User;
import com.lqwu.mallchatserver.user.model.enums.IdempotentEnum;
import com.lqwu.mallchatserver.user.model.enums.ItemEnum;
import com.lqwu.mallchatserver.user.service.UserBackpackService;
import com.lqwu.mallchatserver.user.service.UserService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * 用户注册监听器
 */
@Component
public class UserRegisterListener {
    @Resource
    private UserBackpackService userBackpackService;
    @Resource
    private UserService userService;

    /**
     * 监听用户注册事件
     * 发送改名卡
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserRegisterEvent.class,phase = TransactionPhase.AFTER_COMMIT)
    public void sendCard(UserRegisterEvent event) throws InterruptedException {
        User user = event.getUser();
        userBackpackService.acquireItem(user.getId(), ItemEnum.MODIFY_NAME_CARD.getId(), IdempotentEnum.UID, user.getId().toString());
    }

    /**
     * 监听用户注册事件
     * 发送徽章
     * @param event
     */
    @Async
    @TransactionalEventListener(classes = UserRegisterEvent.class,phase = TransactionPhase.AFTER_COMMIT)
    public void sendBadge(UserRegisterEvent event) throws InterruptedException {
        User user = event.getUser();
        // 判断是否是前十名
        if (userService.lambdaQuery().count() <= 10){
            userBackpackService.acquireItem(user.getId(), ItemEnum.REG_TOP10_BADGE.getId(), IdempotentEnum.UID, user.getId().toString());
        }
        // 判断是否是前100名
        if (userService.lambdaQuery().count() <= 100){
            userBackpackService.acquireItem(user.getId(), ItemEnum.REG_TOP100_BADGE.getId(), IdempotentEnum.UID, user.getId().toString());
        }
    }
}
